package edu.spsu.courses;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import edu.spsu.R;
import edu.spsu.utils.Util;

public class CourseListingActivity extends Activity implements ResponseListener,
	AdapterView.OnItemSelectedListener {
	private static String TAG = CourseListingActivity.class.getName();
	private CourseAdapter courseAdapter;
	private ArrayList<Course> courses = new ArrayList<Course>();
	private String semesterValue = "";
	private String subjectValue = "";
	private boolean firstRun = true;
	
	public final String SUMMER_2012 = "201205";
	public final String SPRING_2012 = "201202";
	public final String FALL_2011 = "201108";
	public final String SUMMER_2011 = "201105";
	public final String SPRING_2011 = "201102";
	public final String FALL_2010 = "201008";
	public final String SUMMER_2010 = "201005";
	public final String SPRING_2010 = "201002";

	private HashMap<String, String> semesterMap = new HashMap<String, String>() {
		{
			put("Summer 2012", SUMMER_2012);
			put("Spring 2012", SPRING_2012);
			put("Fall 2011", FALL_2011);
			put("Summer 2011", SUMMER_2011);
			put("Spring 2011", SPRING_2011);
			put("Fall 2010", FALL_2010);
			put("Summer 2010", SUMMER_2010);
			put("Spring 2010", SPRING_2010);
		}
	};

	private HashMap<String, String> subjectMap = new HashMap<String, String>() {
		{
			put("Select", "");
//			put("ALL Courses", "ALL"); // Takes up too much memory.  I don't wanna deal with the app crashing.
			put("Apparel and Textiles", "ATT");
			put("Accounting", "ACCT");
			put("Anthropology", "ANTH");
			put("Architecture", "ARCH");
			put("Arts", "ARTS");
			put("Astronomy", "ASTR");
			put("Biochemistry", "BIOC");
			put("Biology", "BIOL");
			put("Business Administration", "BUSI");
			put("Chemistry", "CHEM");
			put("Civil Engineering", "CE");
			put("Civil Engineering Technology", "CET");
			put("Communication", "COMM");
			put("Computer Science", "CS");
			put("Computer game design and dev", "CGDD");
			put("Computing & Software Engr", "CSE");
			put("Construction Management", "CM");
			put("Cross Registration", "CROS");
			put("Design Foundation", "DFN");
			put("Distance Learning", "DIST");
			put("E-Core", "ECOR");
			put("Economics", "ECON");
			put("Education", "EDUC");
			put("Elec Tech (Ecore)", "ETEC");
			put("Electrical Engineering", "EE");
			put("Electrical & Computer Eng Tech", "ECET");
			put("Engineering", "ENGR");
			put("Engineering Design Graphics", "EDG");
			put("English", "ENGL");
			put("Environmental Science", "ENVS");
			put("Ethnic Studies", "ES");
			put("French", "FREN");
			put("Geography", "GEOG");
			put("Geology", "GEOL");
			put("History", "HIST");
			put("Honors", "HNRS");
			put("Industrial Engineering Tech", "IET");
			put("Info Tech (WebBSIT)", "WBIT");
			put("Information Design & Comm", "IDC");
			put("Information Technology", "IT");
			put("Management", "MGNT");
			put("Mathematics", "MATH");
			put("Mechanical Engineering", "ME");
			put("Mechanical Engineering Tech", "MET");
			put("Mechanotronics Engineering", "MTRE");
			put("Philosophy", "PHIL");
			put("Physics", "PHYS");
			put("Political Science", "POLS");
			put("Psychology", "PSYC");
			put("Public Speaking", "PUBL");
			put("Quality Assurance", "QA");
			put("Religion", "RELG");
			put("Science, Technology & Society", "STS");
			put("Social & International Studies", "SIS");
			put("Sociology", "SOCI");
			put("Software Engineering", "SWE");
			put("Spanish", "SPAN");
			put("Spsu Orientation", "SPSU");
			put("Surveying", "SURV");
			put("Systems Engineering", "SYE");
			put("Technical Communicaion", "TCOM");
		}
	};

	private final String[] semesters = { "Select Semester", "Summer 2012",
			"Spring 2012", "Fall 2011", "Summer 2011", "Spring 2011",
			"Fall 2010", "Summer 2010", "Spring 2010" };
	//"ALL Courses",
	private final String[] subjects = { "Select Subject", 
			"Accounting", "Anthropology", "Apparel and Textiles",
			"Architecture", "Arts", "Astronomy", "Biochemistry", "Biology",
			"Business Administration", "Chemistry", "Civil Engineering",
			"Civil Engineering Technology", "Communication",
			"Computer Science", "Computer game design and dev",
			"Computing & Software Engr", "Construction Management",
			"Cross Registration", "Design Foundation", "Distance Learning",
			"E-Core", "Economics", "Education", "Elec Tech (Ecore)",
			"Electrical Engineering", "Electrical & Computer Eng Tech",
			"Engineering", "Engineering Design Graphics", "English",
			"Environmental Science", "Ethnic Studies", "French", "Geography",
			"Geology", "History", "Honors", "Industrial Engineering Tech",
			"Info Tech (WebBSIT)", "Information Design & Comm",
			"Information Technology", "Management", "Mathematics",
			"Mechanical Engineering", "Mechanical Engineering Tech",
			"Mechanotronics Engineering", "Philosophy", "Physics",
			"Political Science", "Psychology", "Public Speaking",
			"Quality Assurance", "Religion", "Science, Technology & Society",
			"Social & International Studies", "Sociology",
			"Software Engineering", "Spanish", "Spsu Orientation", "Surveying",
			"Systems Engineering", "Technical Communicaion" };

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.d(TAG,"On Create!!");
		firstRun = true;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.courselisting);

		Spinner semesterSpinner = (Spinner) findViewById(R.id.semesterSpinner);
		Spinner subjectSpinner = (Spinner) findViewById(R.id.subjectSpinner);
		semesterSpinner.setOnItemSelectedListener(this);
		subjectSpinner.setOnItemSelectedListener(this);
		ArrayAdapter<CharSequence> semesterArrayAdapter = new ArrayAdapter<CharSequence>(
				this, android.R.layout.simple_spinner_item, semesters);
		ArrayAdapter<CharSequence> subjectArrayAdapter = new ArrayAdapter<CharSequence>(
				this, android.R.layout.simple_spinner_item, subjects);

		semesterArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		subjectArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		semesterSpinner.setAdapter(semesterArrayAdapter);
		subjectSpinner.setAdapter(subjectArrayAdapter);
		
		courseAdapter = new CourseAdapter(this,courses);
		ListView listView = (ListView)findViewById(R.id.listView1);
		listView.setAdapter(courseAdapter);
//		listView.setOnItemClickListener(new OnItemClickListener(View view) {
//			view.setEnabled(false);
//		});
    	reportLifeCycle("onCreate");
    }
    
    @Override
    protected void onStart() {

    	reportLifeCycle("onStart");
    	super.onStart();
    }

    @Override
    protected void onRestart() {

    	reportLifeCycle("onRestart");
    	super.onRestart();
    }
    
    @Override
    protected void onResume() {

    	reportLifeCycle("onResume");
    	super.onResume();
    	Log.d(TAG,"Courses="+courses.size());
    }

    @Override
    protected void onPause() {
    	super.onPause();
    	reportLifeCycle("onPause");
    }
    
    @Override
    protected void onStop() {
    	super.onStop();
    	reportLifeCycle("onStop");
    }
   
    /** Called when the activity is finished. */
    @Override
    public void onDestroy() {
        super.onDestroy();

    	reportLifeCycle("onDestroy");
    }
    
	private void report(Object o) {
	
	    Util.report(this, TAG, o+"", false);
	}
    
    private void reportLifeCycle(Object o) {

        Util.report(this, TAG, o+" completed successfully", false);
	}
    
    private void reportException(Object o) {

        Util.report(this, TAG, "Exception Thrown: "+o, true);

	}
    
	public void taskBarClick(View v) {
		Util.taskBarClick(v);
	}
    
	public void updateData() {
		Log.d(TAG, "SemesterValue=" + semesterValue + " SubjectValue="
				+ subjectValue);
		HttpPost postRequest = new HttpPost(
				"https://banweb.spsu.edu/pls/PROD/schedule.disp_crse_by_subj");
		// setup post variables
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("cterm_in", semesterValue));
		nameValuePairs.add(new BasicNameValuePair("csubj_in", subjectValue));
		try {
			postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Client.sendRequest(postRequest, this);
	}

//	public void clearData() {
//		courses = new ArrayList<Course>();
//	}

	public void onItemSelected(AdapterView<?> parent, View v, int position,
			long id) {
		Log.d(TAG,"Item Selected!!="+position);
		//*******************************
		if (!firstRun) {
			if (semesterMap.containsKey(parent.getItemAtPosition(position)
					.toString())) {
				semesterValue = semesterMap.get(parent.getItemAtPosition(
						position).toString());
				Log.d(TAG, "SubjectValue=" + subjectValue);
				if (!subjectValue.equals("")) {
					updateData();
				}
			} else if (subjectMap.containsKey(parent
					.getItemAtPosition(position).toString())) {
				subjectValue = subjectMap.get(parent
						.getItemAtPosition(position).toString());
				if (!semesterValue.equals("")) {
					updateData();
				}
			}
		} else {
			firstRun = false;
		}
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		setContentView(R.layout.courselisting);

		Spinner semesterSpinner = (Spinner) findViewById(R.id.semesterSpinner);
		Spinner subjectSpinner = (Spinner) findViewById(R.id.subjectSpinner);
		semesterSpinner.setOnItemSelectedListener(this);
		subjectSpinner.setOnItemSelectedListener(this);
		ArrayAdapter<CharSequence> semesterArrayAdapter = new ArrayAdapter<CharSequence>(
				this, android.R.layout.simple_spinner_item, semesters);
		ArrayAdapter<CharSequence> subjectArrayAdapter = new ArrayAdapter<CharSequence>(
				this, android.R.layout.simple_spinner_item, subjects);

		semesterArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		subjectArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		semesterSpinner.setAdapter(semesterArrayAdapter);
		subjectSpinner.setAdapter(subjectArrayAdapter);
		
		courseAdapter = new CourseAdapter(this,courses);
		ListView listView = (ListView)findViewById(R.id.listView1);
		listView.setAdapter(courseAdapter);
    	reportLifeCycle("onCreate");
	}
	
//    public void addSeparator(TableLayout eventTableLayout) {
//    	TextView listSeparator = new TextView(this);
//    	listSeparator.setTextSize(edu.spsu.events.EventListingActivity.SEPARATOR_SIZE);
//    	listSeparator.setBackgroundColor(edu.spsu.events.EventListingActivity.SEPARATOR_COLOR);
//    	eventTableLayout.addView(listSeparator);
//    }  

	public void onNothingSelected(AdapterView<?> parent) {
		// clearData();
	}

	public void onResponseReceived(ArrayList<Course> processedResponse) {
		processedResponse.remove(0);
		courses = processedResponse;
		Log.d(TAG, "Got a processed response. size=" + processedResponse.size());
		Log.d(TAG,"courses is now size="+courses.size());
		courseAdapter.notifyDataSetChanged();
		courseAdapter = new CourseAdapter(this,courses);
		ListView listView = (ListView)findViewById(R.id.listView1);
		listView.setAdapter(courseAdapter);
//		courseAdapter.notifyDataSetChanged();
//		courses.notifyAll();
	}
}